package com.md.common.utils.web.auth.token;

import com.md.common.utils.web.auth.BaseCodeUtil;
import com.md.common.utils.web.auth.token.exception.TokenInvalidException;
import org.apache.commons.lang3.StringUtils;

import java.util.UUID;

/**
 * 功能描述：访客token处理器
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-7-16 10:46
 * @since JDK 1.8
 */
public class VisitorTokenHandler extends AccessToken {
    private String visitorId;//使用uuid生产唯一标识
    private String token;
    private final String TOKEN_SEPARATOR = "_";

    /**
     * 生成token
     * @return
     */
    public String genToken(){
        this.visitorId = UUID.randomUUID().toString().replace("-","");
        long tokenTime = System.currentTimeMillis();
        String timestamp = StringUtils.reverse(BaseCodeUtil.encodeLongBase64(tokenTime));
        timestamp = BaseCodeUtil.encodeStringBase64(timestamp);
        //混入visitorId
        return BaseCodeUtil.encodeStringBase64(timestamp + TOKEN_SEPARATOR + visitorId);
    }

    /**
     * token解析
     * @throws TokenInvalidException
     */
    public void extract() throws TokenInvalidException {
        if (StringUtils.isBlank(this.token)) {
            throw new TokenInvalidException();
        }
        String tokenStr = BaseCodeUtil.decodeStringBase64(this.token);
        if (StringUtils.isBlank(tokenStr)) {
            throw new TokenInvalidException();
        }
        String visitorId = StringUtils.substringAfter(tokenStr, TOKEN_SEPARATOR);
        if (StringUtils.isEmpty(visitorId)) {
            throw new TokenInvalidException();
        }
        this.visitorId = visitorId;
        String accessToken = StringUtils.substringBefore(tokenStr, TOKEN_SEPARATOR);
        super.setToken(accessToken);
        super.extract();
    }

    public String getVisitorId() {
        return visitorId;
    }

    public void setVisitorId(String visitorId) {
        this.visitorId = visitorId;
    }

    @Override
    public String getToken() {
        return token;
    }

    @Override
    public void setToken(String token) {
        this.token = token;
    }
}
